/**
 * @Project: Runer
 * @Title: MyApplication.java
 * @Package com.runlooker.runer.application
 * @author town
 * @date 2014-5-29 下午8:44:01
 * @Copyright: 2014 www.yineng.com.cn Inc. All rights reserved.
 * @version V1.0
 */
package com.runlooker.runer.application;

import java.io.File;
import java.util.LinkedList;
import java.util.List;

import android.app.ActivityManager;
import android.app.Application;
import android.content.Context;
import android.content.Intent;
import android.database.sqlite.SQLiteDatabase;
import android.os.Environment;

import com.runlooker.runer.broadcast.SysBroadcastReceiver;
import com.runlooker.runer.dao.RosterEntryDao;
import com.runlooker.runer.db.RunerDBOpenHelper;
import com.runlooker.runer.entity.LocalRosterEntity;
import com.runlooker.runer.service.XmppService;
import com.runlooker.runer.ui.base.BaseActivity;
import com.runlooker.runer.ui.chat.FaceConversionUtil;
import com.runlooker.runer.util.L;
import com.runlooker.runer.util.MeasureUtil;
import com.runlooker.runer.util.PreferenceUtils;
import com.runlooker.runer.util.SDCardUtil;

/**
 * @ClassName MyApplication
 * @Description 模块描述
 * @author town
 * @Date 2014-5-29
 */
public class MyApplication extends Application {
	private final static String tag = MyApplication.class.getSimpleName();

	// 存储到PreferenceUtils中的key名,两个登录状态
	// public final static String AUTHENTICATED_STATE = "login_state";
	// 两个验证状态值:验证成功，验证失败（包括主动退出）,验证中
	public final static String AUTHENTICATED_SUCCESS = "login_success";
	public final static String AUTHENTICATED_FAILED = "login_out";
	public final static String AUTHENTICATED_ING = "loging";

	public final static int message_size = 200;// 每次发送的字符个数

	/**
	 * 标识成功
	 */
	public final static int SUCCESS = 1024;
	/**
	 * 标识异常
	 */
	public final static int EXCEPTION = 2046;
	/**
	 * 标识失败
	 */
	public final static int FAILED = 512;

	/**
	 * 注册端口
	 */
	public final static int PORT = 5222;

	/**
	 * 家里服务器地址
	 */
	// public final static String SERVER_IP = "192.168.0.111";
	

	
	/**
	 * 公共服务器地址
	 */
	public final static String SERVER_IP = "123.56.84.221 ";
	// public final static String CUSTOM_SERVER = "www.runlooker.com";

	/**
	 * 是否打印日志
	 */
	public final static boolean DEBUG = true;

	private static String APPLICATION_FILE_PATH = Environment
			.getExternalStorageDirectory().getPath()
			+ File.separator
			+ "com.runlooker.runer" + File.separator;
	private static String TEMP;// 临时文件保存路径
	private static String IMAGE_SAVE_PATH = APPLICATION_FILE_PATH + "images"
			+ File.separator;// 接收到的图片保存路径
	private static String PORTRAIT_SAVE_PATH = APPLICATION_FILE_PATH
			+ "Headportrait" + File.separator;// 头像保存路径
	private static String VOICE_SAVE_PATH = APPLICATION_FILE_PATH + "voice"
			+ File.separator;// 聊天音频文件保存路径

	// Enum RosterPacket.ItemStatus: subscribe,unsubscribe
	public static int subscribe = 0; // 发送者希望订阅接收者的出席信息

	public static int unsubscribe = 1; // 发送者不再可通讯

	// Enum RosterPacket.ItemType: both,from,none,remove,to
	public static int both = 0; //
	public static int from = 1; //
	public static int none = 2; //
	public static int remove = 3; //
	public static int to = 4; //

	/** Preference key for account username. */
	public static final String ACCOUNT_USERNAME_KEY = "account_username";
	/** Preference key for account password. */
	public static final String ACCOUNT_PASSWORD_KEY = "account_password";
	public static final String STATUS_MESSAGE = "status_message";
	public static final String AVAILABLE = "available";
	public static final String STATUS_MODE = "status_mode";
	public static final String PRIORITY = "account_prio";

	// private List<BaseActivity> mActivityList = new
	// LinkedList<BaseActivity>();
	//
	// public void addActivity(BaseActivity activity) {
	// mActivityList.add(activity);
	// }
	//
	// public void removeActivityFromList(BaseActivity activity) {
	// mActivityList.remove(activity);
	// }
	//
	// public void closeAllActivity() {
	// for (BaseActivity activity : mActivityList) {
	// activity.finish();
	// }
	// }

	/**
	 * set application folders path by sdcard mount state
	 * 
	 * @param context
	 * @param flag
	 *            true is mounte, false is not mounte
	 */
	public static void setDirPath(Context context, boolean flag) {
		if (!SDCardUtil.isExistSDCard()
				|| !SDCardUtil.isExternalStorageReadable()
				|| !SDCardUtil.isExternalStorageWritable()) {
			IMAGE_SAVE_PATH = context.getFilesDir() + "images" + File.separator;// 接收到的图片保存路径
			PORTRAIT_SAVE_PATH = context.getFilesDir() + "Headportrait"
					+ File.separator;// 头像保存路径
			VOICE_SAVE_PATH = context.getFilesDir() + "voice" + File.separator;// 聊天音频文件保存路径
		} else {
			IMAGE_SAVE_PATH = APPLICATION_FILE_PATH + "images" + File.separator;// 接收到的图片保存路径
			PORTRAIT_SAVE_PATH = APPLICATION_FILE_PATH + "Headportrait"
					+ File.separator;// 头像保存路径
			VOICE_SAVE_PATH = APPLICATION_FILE_PATH + "voice" + File.separator;// 聊天音频文件保存路径
		}
	}

	/**
	 * @see android.app.Application#onCreate()
	 */
	@Override
	public void onCreate() {
		super.onCreate();
		new Thread(new Runnable() {
			@Override
			public void run() {
				FaceConversionUtil.getInstace().getFileText(MyApplication.this);
			}
		}).start();

		TEMP = getCacheDir() + "temp" + File.separator;
		/*
		 * if no sdcard or can't read or can't write, so Save Files on Internal
		 * Storage
		 */
		if (!SDCardUtil.isExistSDCard()
				|| !SDCardUtil.isExternalStorageReadable()
				|| !SDCardUtil.isExternalStorageWritable()) {
			setDirPath(this, false);
		} else {
			setDirPath(this, true);
		}

		Intent intent = new Intent(this, XmppService.class);
		startService(intent);
	}

	/**
	 * get image folder save path
	 * 
	 * @return
	 */
	public static String getImageSavePath() {

		return IMAGE_SAVE_PATH;
	}

	/**
	 * get voice folder save path
	 * 
	 * @return
	 */
	public static String getVoiceSavePath() {

		return VOICE_SAVE_PATH;
	}

	/**
	 * 
	 * get temp folder save path
	 * 
	 * @return
	 */
	public static String getTempPath() {
		return TEMP;
	}

	/**
	 * get Portrait folder save path
	 * 
	 * @return
	 */
	public static String getPortraitSavePath() {

		return PORTRAIT_SAVE_PATH;
	}

	public static String getMyAccount(Context context) {
		return PreferenceUtils.getPrefString(context,
				MyApplication.ACCOUNT_USERNAME_KEY, "");
	}

	/**
	 * 确认帐号、密码是否在本地保存（方便自动登录）
	 * 
	 * @return false if there is no account configured.
	 */
	public static boolean isAccountConfigured(Context context) {
		String password = PreferenceUtils.getPrefString(context,
				MyApplication.ACCOUNT_PASSWORD_KEY, "");
		boolean issAccountConfigured = false;
		if (password.length() > 0) {
			issAccountConfigured = true;
		}
		return issAccountConfigured;
	}

	public static boolean isServiceRunning(Context mContext, String className) {
		boolean isRunning = false;
		ActivityManager activityManager = (ActivityManager) mContext
				.getSystemService(Context.ACTIVITY_SERVICE);
		List<ActivityManager.RunningServiceInfo> serviceList = activityManager
				.getRunningServices(300);
		if (!(serviceList.size() > 0)) {
			return false;
		}
		for (int i = 0; i < serviceList.size(); i++) {
			if (serviceList.get(i).service.getClassName().equals(className)) {
				return true;
			}
		}
		return isRunning;
	}

	public static boolean isSelf(Context context, String account) {
		boolean Flag;
		if (account != null
				&& account.equals(PreferenceUtils.getPrefString(context,
						MyApplication.ACCOUNT_USERNAME_KEY, ""))) {
			Flag = true;
		} else {
			Flag = false;
		}
		return Flag;
	}

	/**
	 * 
	 * 订阅了别人/互相订阅
	 * 
	 * @param context
	 * @param account
	 * @return
	 */
	public static boolean subscribe(Context context, String account) {
		boolean flag = false;
		RosterEntryDao dao = new RosterEntryDao(context);
		LocalRosterEntity rosterEntry = dao.getRoster(account);
		if (rosterEntry != null) {
			switch (rosterEntry.getItemType()) {
			case LocalRosterEntity.NONE:// 互相未订阅
				flag = false;
				break;
			case LocalRosterEntity.FROM:// 别人订阅了自己
				flag = false;
				break;
			case LocalRosterEntity.BOTH:// 互相订阅
				flag = true;
				break;
			case LocalRosterEntity.REMOVE:// 从条目中删除Roster
				flag = false;
				break;
			case LocalRosterEntity.TO:// 自己订阅了别人
				flag = true;
				break;
			default:
				flag = false;
				break;
			}
		} else {
			flag = false;
		}

		return flag;
	}
}
